﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Niaofei.Core;
using System.IO;
using System.Reflection;
using System.Windows;

namespace Niaofei.WPF.Main
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        [STAThread]
        private static void Main(string[] args)
        {
            MainAsync(args).GetAwaiter().GetResult();
        }

        private static async Task MainAsync(string[] args)
        {
            AppDomain.CurrentDomain.AssemblyResolve += OnAssemblyResolve;

            using var host = CreateHostBuilder(args).Build();
            await host.StartAsync().ConfigureAwait(true);
            var app = new App();
            app.InitializeComponent();
            app.MainWindow = host.Services.GetRequiredService<MainWindow>();
            app.MainWindow.Visibility = Visibility.Visible;
            app.Run();

            await host.StopAsync().ConfigureAwait(true);
        }

        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            return Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((h, c) =>
                {

                })
                .ConfigureServices(services =>
                {
                    var assemblys = AppDomain.CurrentDomain.GetAssemblies();
                    services.InjectionService(assemblys);

                    var extensionPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "extension");
                    var extensionFiles = Directory.GetFiles(extensionPath, "*.dll");

                    var extensionAssemblys = extensionFiles.Select(m => Assembly.LoadFile(m)).ToArray();
                    services.InjectionService(extensionAssemblys);
                });
        }

        private static Assembly? OnAssemblyResolve(object? sender, ResolveEventArgs args)
        {
            if (args?.RequestingAssembly?.Location != null)
            {
                var path = Path.GetDirectoryName(args.RequestingAssembly.Location);

                var assName = new AssemblyName(args.Name);
                var filePath = Path.Combine(path!, $"{assName.Name}.dll");

                if (File.Exists(filePath)) 
                {
                    return Assembly.LoadFile(filePath);
                }
            }

            return null;
        }
    }
}
